﻿// <com.woyouqiu.Copyright>
// --------------------------------------------------------------
// <copyright>上海有求网络科技有限公司 2015</copyright>
// <Solution>Vecen.BangChuang</Solution>
// <Project>Vecen.BangChuang.Web.Host</Project>
// <FileName>NullToEmptyListResolver.cs</FileName>
// <CreateTime>2017-05-04 15:11</CreateTime>
// <Author>何苗</Author>
// <Email>hemiao@woyouqiu.com</Email>
// <log date="2017-05-04 15:11" version="00001">创建</log>
// --------------------------------------------------------------
// </com.woyouqiu.Copyright>

using System;
using System.Collections;
using System.Reflection;
using Newtonsoft.Json.Serialization;

namespace Vecen.BangChuang.Json {
    public class NullToEmptyResolver: DefaultContractResolver {
        protected override IValueProvider CreateMemberValueProvider(MemberInfo member) {
            IValueProvider provider = base.CreateMemberValueProvider(member);
            var propertyInfo = (PropertyInfo)member;
            if(propertyInfo.PropertyType == typeof(string) || propertyInfo.PropertyType.GetTypeInfo().IsValueType) {
                return new EmptyStringValueProvider(provider);
            }
            if(propertyInfo.PropertyType.IsArray) {
                return new EmptyListValueProvider(provider, propertyInfo.PropertyType);
            }
            if(propertyInfo.PropertyType.GetTypeInfo().GetInterface(nameof(IEnumerable)) != null) {
                return new EmptyListValueProvider(provider, propertyInfo.PropertyType);
            }
            return provider;
        }
    }
}